package com.p2p.handler;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

public class PeerJsHandshakeInterceptor implements HandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 处理原始URI中的特殊字符
        String originalUri = request.getURI().toString();
        String fixedUri = fixPeerJsUri(originalUri);

        // 替换请求中的URI
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            attributes.put("fixedUri", new URI(fixedUri));
        }
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                              WebSocketHandler wsHandler, Exception exception) {}

    // 修复PeerJS可能产生的未编码特殊字符
    private String fixPeerJsUri(String originalUri) {
        // 替换{和}为编码值，其他特殊字符可按需添加
        return originalUri
                .replace("{", "%7B")
                .replace("}", "%7D")
                .replace("|", "%7C") // 其他可能的特殊字符
                .replace("^", "%5E");
    }
}
